<?php

namespace App\Services;

use App\Models\ActiveApply;

class ActiveApplyService
{
    const PENDING = 0;//待处理
    const PASS = 1;//通过
    const REJECTED = 2;//拒绝

    public static function formatApply($data)
    {
        foreach ($data as $k => $datum) {
            $data[$k]['status'] = static::getStatusByName($data[$k]['status']);
        }
        return $data;
    }

    /**
     *根据status获取状态名称
     */
    public static function getStatusByName($name)
    {
        $status = [
            self::PENDING => '待处理',
            self::PASS => '通过',
            self::REJECTED => '已拒绝'
        ];
        return $status[$name];
    }

    /**
     * 获取优惠申请
     */
    public static function getActiveApply($id, $params)
    {
        $page = isset($attrs['page']) ? $params['page'] : 1;
        $pageSize = isset($attrs['page_size']) ? $params['page_size'] : 20;
        // 参数格式化
        list($where, $between) = self::parseParams($id, $params);
        $select = [
            "active_name",
            "coupon_amount",
            "created_at",
            "remark",
            "status",
        ];
        $sqlObj = ActiveApply::select($select)
            ->where($where)
            ->orderBy("created_at", "desc");
        if (!empty($between)) {
            $sqlObj->whereBetween('created_at', $between);
        }
        $re = get_page_data($sqlObj, $page, $pageSize);
        return $re;
    }

    public static function parseParams($userId, $attrs)
    {
        $between = $whereIn = [];
        $where[] = ['user_id', '=', $userId];
        if (isset($attrs['time_begin'])) {
            $between['time_begin'] = date('Y-m-d H:i:s', strtotime($attrs['time_begin']));
        } else {
            $between['time_begin'] = date('Y-m-d 00:00:00');
        }
        if (isset($attrs['time_end'])) {
            $between['time_end'] = date('Y-m-d H:i:s', strtotime($attrs['time_end']));
        } else {
            $between['time_end'] = date('Y-m-d 23:59:59');
        }
        if (isset($attrs['status'])) {
            $where[] = ['status', $attrs['status']];
        }
        return [$where, $between];
    }

}
